﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using CommDll;

namespace HospitalMedicineTraceability
{
    /// <summary>
    /// ClassName:frmQuery_GoodsCodeCheck
    /// Version:1.0
    /// Date:2024-08-26
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为处理His商品对码信息
    /// </remarks>
    public partial class frmQuery_GoodsCodeCheck : DevComponents.DotNetBar.OfficeForm
    {
        #region 01.自定义属性
        public DataTable m_dt;  // 保存查询出来的数据
        private string m_strWhere = "";  // 固定条件
        private int m_nRowsIndex0 = -1; // 明细单用
        private Timer m_timerShowData = new Timer();        
        #endregion
        public frmQuery_GoodsCodeCheck()
        {
            InitializeComponent();
            m_timerShowData.Enabled = true;
            m_timerShowData.Interval = 10;
            m_timerShowData.Tick += new System.EventHandler(timerShowData_Tick);
        }
        #region 02.自定义方法

        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strFieldName = "", strFieldSql = "", strFieldWidth = "";
            // 1 主数据表格
            string strDgvName = this.Name + "_01";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strDgvName))
            {
                AppConfig._initDictField(strDgvName);
                //return;
            }
            // 默认值
            strFieldName = "Code-商品编号,Name-商品名称,PackageSpec-规格,Unit-单位,Form-剂型,Manufacturer-生产厂家,PackageRatio-包装比,CheckStatus-对码状态,SupervisionCodeCount-对码数量,SupervisionCode-电监码(前7位)";
            strFieldSql = "Code,Name,PackageSpec,Unit,Form,Manufacturer,PackageRatio,CheckStatus,SupervisionCodeCount,SupervisionCode";            
            strFieldWidth = "80,150,150,80.80,200,120";
            AppConfig.m_dictFieldName.Add(strDgvName, strFieldName);            
            AppConfig.m_dictFieldSql.Add(strDgvName, strFieldSql);
            AppConfig.m_dictField0.Add(strDgvName, strFieldSql);            
            AppConfig.m_dictFieldWidth0.Add(strDgvName, strFieldWidth);
            // 设置值
            strFieldSql = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strDgvName), AppConfig.m_dictField0[strDgvName]).Trim();
            AppConfig.m_dictField.Add(strDgvName, strFieldSql);
            strFieldWidth = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strDgvName), AppConfig.m_dictFieldWidth0[strDgvName]).Trim();
            AppConfig.m_dictFieldWidth.Add(strDgvName, strFieldWidth);
            // 02 右键双击设置显示方式
            this.dgvMain.Tag = strDgvName;
            this.dgvMain.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(DataDeal.dataGridView_MouseDoubleClick);
            // 03 其他事件
            this.dgvMain.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(CommFun._dgvColumnHeaderSort);// 排序
            this.dgvMain.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(CommFun._dgvRowEnter);// 改变行颜色

            // 2 明细数据表格
            strDgvName = this.Name + "_02";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strDgvName))
            {
                AppConfig._initDictField(strDgvName);
                //return;
            }
            // 默认值
            strFieldName = "Id-序号,SupervisionCode-电监码(前7位),Name-商品名称,PackageSpec-规格,Unit-单位,Manufacturer-生产厂家,PackageName-包装名称,PackageRatio-包装比,CreateTime-对码时间";
            strFieldSql = "Id,SupervisionCode,Name,PackageSpec,Unit,Manufacturer,PackageName,PackageRatio,CreateTime";
            strFieldWidth = "0,120,150,150,80,200,120";
            AppConfig.m_dictFieldName.Add(strDgvName, strFieldName);
            AppConfig.m_dictFieldSql.Add(strDgvName, strFieldSql);
            AppConfig.m_dictField0.Add(strDgvName, strFieldSql);
            AppConfig.m_dictFieldWidth0.Add(strDgvName, strFieldWidth);
            // 设置值
            strFieldSql = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strDgvName), AppConfig.m_dictField0[strDgvName]).Trim();
            AppConfig.m_dictField.Add(strDgvName, strFieldSql);
            strFieldWidth = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strDgvName), AppConfig.m_dictFieldWidth0[strDgvName]).Trim();
            AppConfig.m_dictFieldWidth.Add(strDgvName, strFieldWidth);
            // 02 右键双击设置显示方式
            this.dgvDetail.Tag = strDgvName;
            this.dgvDetail.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(DataDeal.dataGridView_MouseDoubleClick);
            // 03 其他事件
            this.dgvDetail.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(CommFun._dgvColumnHeaderSort);// 排序
            this.dgvDetail.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(CommFun._dgvRowEnter);// 改变行颜色
        }

        private void timerShowData_Tick(object sender, EventArgs e)
        {
            m_timerShowData.Enabled = false;
            _initPharmacy();
        }

        /// <summary>
        /// 初始化药房信息信息
        /// </summary>
        private void _initPharmacy()
        {
            cbbCheckStatus.DrawItem += new System.Windows.Forms.DrawItemEventHandler(CommFun._cbbDrawItem);
            _query();
        }      

        /// <summary>
        /// 取查询条件
        /// </summary>
        private Boolean _getQueryWhere(ref string strWhere)
        {
            Boolean bResult = false;
            string strTemp = "";
            // 00 取名称
            if (cbGoodsName.Checked && !cbbGoodsName.Text.Trim().Equals(""))
            {
                strTemp = cbbGoodsName.Text.Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(Name like '%{0}%' or dbo.F_GetSpellCN(Name) like '%{0}%' or A.Code = '{0}')", strTemp);
                }
            }

            // 01 生产厂家
            if (cbManufacturer.Checked && !txtManufacturer.Text.Trim().Equals(""))
            {
                strTemp = txtManufacturer.Text.Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(Manufacturer like '%{0}%')", strTemp);
                }
            }

            // 02 电监码
            if (cbSupervisionCode.Checked && !txtSupervisionCode.Text.Trim().Equals(""))
            {
                strTemp = txtSupervisionCode.Text.Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(SupervisionCode like '%{0}%')", strTemp);
                }
            }            
            bResult = true;
            return bResult;
        }

        /// <summary>
        /// 取查询条件(复核人等)
        /// </summary>
        private Boolean _getQueryWhere1(ref string strWhere)
        {
            strWhere = "";
            Boolean bResult = false;
            string strTemp = "";
            // 发票类别
            if (cbCheckStatus.Checked && cbbCheckStatus.SelectedIndex > -1)
            {
                strTemp = cbbCheckStatus.Text.Split('|')[0].Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(CheckStatus = '{0}')", strTemp);
                }
            }            
            bResult = true;
            return bResult;
        }

        /// <summary>
        /// 信息查询
        /// </summary>
        private void _query()
        {
            if (m_dt != null)
            {
                m_dt.Dispose();
            }
            // 00 取条件:有参数时按参数来取数据
            string strWhere = m_strWhere;
            string strWhere1 = "";
            if (_getQueryWhere(ref strWhere))
            {
                if (!strWhere.Equals(""))
                {
                    strWhere = string.Format(" and {0}", strWhere);
                }
                // 取配送人条件
                _getQueryWhere1(ref strWhere1);
                if (!strWhere1.Equals(""))
                {
                    strWhere1 = string.Format(" and {0}", strWhere1);
                }
                // 02 取数据
                string strSql = string.Format(@"
                    select {0} from
                    (
                       select A.*
,CheckStatus= case when isnull(B.Code,'') = '' then '未对码' else '已对码' end
,SupervisionCodeCount = isnull(B.SupervisionCodeCount,0)
,SupervisionCode
from TH_Goods A
left outer join (
select Code,SupervisionCodeCount = Count(*),SupervisionCode = stuff((select ',' + SupervisionCode from TH_GoodsCheckSupervisionCode AA where AA.Code = A.Code for xml path('')),1,1,'')
from TH_GoodsCheckSupervisionCode A group by Code
) B On A.Code = B.Code
where 1=1
                       {{0}}
                    )A where 1=1 {{1}} order by Code
                "
                , AppConfig.m_dictFieldSql[dgvMain.Tag.ToString()]);                
                strSql = string.Format(strSql, strWhere, strWhere1);
                m_dt = AppInfo._openSql_DataTable(strSql);

            }
            // 03 显示数据
            DataTable dt = null;
            if (m_dt != null)
            {
                dt = m_dt.Copy();
            }
            _showData(dt);
        }

        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="dt"></param>
        private void _showData(DataTable dt)
        {
            m_nRowsIndex0 = -1;
            if (dgvDetail.Rows.Count > 0)
            {
                ((DataTable)dgvDetail.DataSource).Rows.Clear();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                dt.Columns["SupervisionCodeCount"].ReadOnly = false;
                dt.Columns["CheckStatus"].ReadOnly = false;
                // 0101 调整字段顺序
                CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[dgvMain.Tag.ToString()]);
                // 0102 显示数据
                CommFun._showDataGridView(dgvMain, dt, AppConfig.m_dictFieldWidth[dgvMain.Tag.ToString()], AppConfig.m_dictFieldName[dgvMain.Tag.ToString()]); 
            }
            else {
                // 清除数据
                DataTable dtTemp = (DataTable)dgvMain.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }      
            }
            gbMain.Text = string.Format("商品信息【记录数:{0}】", dgvMain.Rows.Count);
        }

        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="dt"></param>
        private void _showDetail()
        {
            // 00 清除数据
            if (dgvDetail.Rows.Count > 0)
            {
                DataTable dtTemp = (DataTable)dgvDetail.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }
            }
            // 01 按编号取数据
            if (m_nRowsIndex0 >= 0)
            {
                string strInvoiceCode = "";
                strInvoiceCode = dgvMain.Rows[m_nRowsIndex0].Cells["Code"].Value.ToString();
                try
                {
                    string strSql = @"select {0} from 
                     (
                        select * from TH_GoodsCheckSupervisionCode where Code = '{1}'
                     )A order by CreateTime desc";
                    strSql = string.Format(strSql, AppConfig.m_dictFieldSql[dgvDetail.Tag.ToString()], strInvoiceCode);
                    DataTable dt = AppInfo._openSql_DataTable(strSql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        // 0101 调整字段顺序
                        CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[dgvDetail.Tag.ToString()]);
                        // 0102 显示数据
                        CommFun._showDataGridView(dgvDetail, dt, AppConfig.m_dictFieldWidth[dgvDetail.Tag.ToString()], AppConfig.m_dictFieldName[dgvDetail.Tag.ToString()]);
                    }
                }
                catch (Exception ex)
                {
                    CommFun._messageBoxShow(ex.Message);
                    return;
                }
            }
            gbDetail.Text = string.Format("对码明细信息(双击删除对码信息)【记录数:{0}】", dgvDetail.Rows.Count);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void _init()
        {
            // 01 dataGridViewX1设为不可编辑
            dgvMain.ReadOnly = true;
            //dgvMain.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
 
            // 03 初始化DataGridView
            _initDgvTitle();

            // 06 splitContainer1
            dgvMain.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top
                    | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom));
            splitContainer1.Tag = this.Name + "_splitContainerHeight";
            splitContainer1.SplitterDistance = FunctionComm._strToInt(AppConfig.m_iniSetup._readValue("Common", splitContainer1.Tag.ToString(), splitContainer1.SplitterDistance.ToString()).Trim(), splitContainer1.SplitterDistance);
            splitContainer1.SplitterMoved += DataDeal.splitContainer_SplitterMoved;
        }
        #endregion

        #region 03.系统事件方法

        private void frm_Load(object sender, EventArgs e)
        {
            _init();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            // 数据查询
            _query();           
        }
        #endregion

        #region GridViewX事件
        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender,e);
            // 显示明细
            if (!(e.RowIndex < 0 || e.ColumnIndex < 0))
            {
                if (m_nRowsIndex0 != e.RowIndex)
                {
                    m_nRowsIndex0 = e.RowIndex;
                    _showDetail();
                }
            } 
        }

        #endregion

        private void dgvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                e.Handled = true;
            }               
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (dgvMain != null && dgvMain.Rows.Count > 0)
            {
                CommFun._ExportExcel("", dgvMain);
            }
        }

        private void dgvDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            else
            {
                if (CommFun._messageBoxShow("确认删除该对码信息？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    string strId = dgvDetail.CurrentRow.Cells["Id"].Value.ToString();
                    string strSql = string.Format("delete from TH_GoodsCheckSupervisionCode where Id = '{0}'", strId);
                    AppInfo._execSql(strSql);
                    CommFun._messageBoxShow("对码信息删除成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgvDetail.Rows.Remove(dgvDetail.CurrentRow);
                    //dgvMain.Columns["SupervisionCodeCount"].ReadOnly = false;
                    //dgvMain.Columns["CheckStatus"].ReadOnly = false;
                    dgvMain.CurrentRow.Cells["SupervisionCodeCount"].Value = FunctionComm._strToInt(dgvMain.CurrentRow.Cells["SupervisionCodeCount"].Value.ToString()) - 1;
                    if (dgvMain.CurrentRow.Cells["SupervisionCodeCount"].Value.ToString().Equals("0")) {
                        dgvMain.CurrentRow.Cells["CheckStatus"].Value = "未对码";
                    }

                }                           
            }
        }

        private void btnCodeCheck_Click(object sender, EventArgs e)
        {
            frmGoodsCodeCheck_Single frm = new frmGoodsCodeCheck_Single();
            frm.ShowDialog();
        }
    }
}